//
//  MJTComposePictureView.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/19.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
//  重用标记
private let MJTComposePictureViewCellIdentifier = "MJTComposePictureViewCellIdentifier"
//  发微博界面配图
class MJTComposePictureView: UICollectionView {

    //  点击加号按钮闭包
    var selectedAddButtonClosure: (()->())?
    //懒加载图片数据
    lazy var images: [UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        //默认隐藏
        hidden = true
        backgroundColor = RandomColor()
        //注册cell
        registerClass(MJTComposePictureViewCell.self, forCellWithReuseIdentifier: MJTComposePictureViewCellIdentifier)
        //设置数据源代理
        dataSource = self
        delegate = self
    }
    func addImage(image: UIImage) {
        if images.count > 9 {
            return
        }
        hidden = false
        images.append(image)
        reloadData()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        // 间距
        let itemMargin: CGFloat = 5
        // 每项大小
        let itemWidth = (width - 2 * itemMargin) / 3
        //正方形
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
    }
}
extension MJTComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9 {
            return images.count
        } else {
            return images.count + 1
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MJTComposePictureViewCellIdentifier, forIndexPath: indexPath) as! MJTComposePictureViewCell
        if indexPath.item == images.count {
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        //设置闭包
        cell.deleteImageClosure = { [weak self] in
            self?.images.removeAtIndex(indexPath.item)
            if self?.images.count > 0 {
                self?.reloadData()
            } else {
                self?.hidden = true
            }
        }
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.item == images.count {
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)

          selectedAddButtonClosure?()
        }
    }
}
//自定义发微博
class MJTComposePictureViewCell: UICollectionViewCell {
     var deleteImageClosure: (()->())?
    //数据模型
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            } else  {
                imageView.image = image
                imageView.highlightedImage = nil
                deleteButton.hidden = false
            }
        }
    }
    //显示图片
    private lazy var imageView: UIImageView = UIImageView()
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    //MARK:  点击事件
    @objc private func deleteButtonAction() {
        deleteImageClosure?()
    }
}






